﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;

public class TextureSaveAsPNG : EditorWindow
{
    [MenuItem("TA/辅助/保存png")]
    static void SwapUVTextures()
    {
        Object[] selected = Selection.objects;
        if (selected == null || selected.Length == 0)
        {
            EditorUtility.DisplayDialog("错误", "请至少选中一张 Texture2D 图片", "好");
            return;
        }

        foreach (var obj in selected)
        {
            Texture2D tex = obj as Texture2D;
            if (tex == null) continue;

            string assetPath = AssetDatabase.GetAssetPath(tex);
            string fullPath = Path.Combine(Directory.GetCurrentDirectory(), assetPath);
            string dir = Path.GetDirectoryName(fullPath);
            string fileName = Path.GetFileNameWithoutExtension(fullPath);
            string invPath = Path.Combine(dir, fileName + "_new.png");

            Texture2D readableTex = GetReadableTexture(tex);
            if (readableTex == null)
            {
                Debug.LogWarning($"跳过无法读取的贴图: {assetPath}");
                continue;
            }

    
            byte[] invBytes = readableTex.EncodeToPNG();
            File.WriteAllBytes(invPath, invBytes);

            Debug.Log($"生成贴图: {invPath}");
        }

        AssetDatabase.Refresh();
        EditorUtility.DisplayDialog("完成", "已生成所有贴图的 UV 翻转版本（U↔V）", "好");
    }

    static Texture2D GetReadableTexture(Texture2D source)
    {
        RenderTexture rt = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
        Graphics.Blit(source, rt);

        RenderTexture prev = RenderTexture.active;
        RenderTexture.active = rt;

        Texture2D tex = new Texture2D(source.width, source.height, TextureFormat.RGBA32, false, false); // false = sRGB
        tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
        tex.Apply();

        RenderTexture.active = prev;
        RenderTexture.ReleaseTemporary(rt);

        return tex;
    }

    static Texture2D SwapUV(Texture2D original)
    {
        int width = original.width;
        int height = original.height;
        Texture2D result = new Texture2D(height, width, TextureFormat.RGBA32, false, false); // 宽高互换

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                Color c = original.GetPixel(x, y);
                result.SetPixel(y, x, c); // 交换 UV
            }
        }

        result.Apply();
        return result;
    }
}
